
<template>
	<div class="index">
		
		<div class="center"> 
			<left></left>
			<div class="right">
          <top></top> 
          <!-- <div class="hei10"></div>
          <div class="where" style="background: #fff; padding: 10px 30px; font-size: 14px; color: #595959;">当前位置：分销后台>直播打卡</div>
          --><div class="hei10"></div>
		  		 
		  
                <div class="t_table_box">
					<div style="background-color: rgb(218, 231, 245);color:rgb(100, 112, 118);padding: 10px 20px;font-size: 14px;margin-bottom:20px;">
						直播统计可以帮助您便捷的统计主播绩效，且可以实时显示主播当前直播销售情况
						<el-button @click="downDate" type="text" style="margin-left:30px;"><i class="el-icon-download"></i>点击这里下载使用说明</el-button>
					</div>
					<div style="display: flex;justify-content: space-between;">
						<el-button @click="daka" style="margin-bottom: 20px;" type="danger">直播打卡</el-button>
						<el-button @click="tozbgl" style="margin-bottom: 20px;"  type="danger">主播管理</el-button>
					</div>
                    <el-table
                        :header-cell-style="{
                        background:'#F4F4F4',
                        color:'#7D8087'}"
                        :data="tableData"
                        stripe
                        style="width: 100%">
                        <el-table-column
                        prop="name"
                        label="直播中">
                        </el-table-column>
                        <el-table-column
                        prop="type"
                        label="直播类型">
                        </el-table-column>
						<el-table-column
                        prop="title"
                        label="直播标题">
                        </el-table-column>
						<el-table-column
						width="200px"
                        prop="created_at"
                        label="开播时间">
                        </el-table-column>
						<el-table-column label="直播时长">
							<template slot-scope="scope">
								{{timediff(scope.row.created_at)}}
							</template>
                        </el-table-column>
						<el-table-column
                        prop="sales"
                        label="销量">
                        </el-table-column>
                        <el-table-column label="操作">
							<template slot-scope="scope">
								<el-button
								size="mini"
								type="text"
								@click="handleEdit( scope.row.id)">下播</el-button>
								<el-button
								size="mini"
								type="text"
								@click="replace(scope.row)">换人续播</el-button>
							</template>
                        </el-table-column> 
                    </el-table>
                </div>
			</div>
		</div>
		<!-- <foot></foot> -->
		<!-- 打开弹窗 -->
        <el-dialog
        title="直播打卡"
        :visible.sync="dakashow"
        width="600px">
            <div class="t_daka_box">
                <div>
                    <el-select v-model="choosezb"
					value-key="id"  class="t_select_box"  placeholder="请选择主播">
                        <el-option v-for="(item,index) in zblistdata" :key="index" :label="item.name" :value="item"></el-option>
                    </el-select>
                    <el-select @change="nowtype"
					:disabled="isreplace"
					v-model="choosezbtype" class="t_select_box"
                    style="margin-top: 20px;margin-bottom:20px"
					value-key="label"
                    placeholder="请选择直播类型">
						<el-option v-for="(item,index) in zbtypedata" :key="index" :label="item.label" :value="item"></el-option>
                    </el-select>
                    <el-select :disabled="isreplace" v-model="choosezbtitle" class="t_select_box" value-key="label" filterable placeholder="请选择销售页名称或店铺名">
                        <el-option v-for="(item,index) in zbtitledata" :key="index" :label="item.label" :value="item"></el-option>
                    </el-select>
					<router-link to="/addliucheng">
						<el-button type="text">没有找到直播间？</el-button>
					</router-link>
                </div>
                <div @click="startzb" class="t_daka_btn">
                    开始直播
                </div>
            </div>
        </el-dialog>

	</div>
</template>

<script>
	import axios from 'axios'
	import top from '@/components/top.vue'
	import left from '@/components/left.vue'
	import foot from '@/components/foot.vue'


	export default {
		components: {
			"left": left,
			"top": top,
			"foot": foot
		},
		name: 'productionBasismanagDj',
		data() {
			return{
				tableData: [],
                dakashow:false,
				zblistdata:[],
				choosezb:'',
				zbtypedata:[],
				choosezbtype:'',
				zbtitledata:[],
				choosezbtitle:'',
				xunhuan:'',
				isreplace:false,
				replaceid:'',
				ws:null

			}
		},
		created() {
			
			
			
			//主播列表
			this.zblist()
			//直播类型
			this.zbtype()

			//在播列表
			// this.getlist()
			//地址配置,用于下载模板
			if (window.location.href.indexOf("91haoka_platform") > -1) {
				console.log("线上项目，谨慎操作。")
				this.url = window.location.origin + "/91haoka_platform/"
			} else {
				this.url = ""
			}

			console.log('----')
			//ws://222.173.219.2:8995   测试
			//wss://ws.91haoka.cn:8995   正式
			this.ws = new WebSocket('wss://ws.91haoka.cn:8995');
			//链接socket
			this.socket()
			
			

		},
		beforeDestroy() {
			clearInterval(this.xunhuan);
			this.xunhuan=''
			//完成通信后关闭WebSocket连接
			this.ws.close();
		},
		methods: {
			
			socket(){
				var that = this

				console.log(window.location.host)
				// 获取连接状态
				
				// console.log('ws连接状态1：' + this.ws.readyState);
				//监听是否连接成功
				this.ws.onopen = function () {
					console.log('ws连接状态2：' + that.ws.readyState);
					//连接成功则发送登录请求
					let message =  {"type":"live-stream",'shop_id':JSON.parse(localStorage.getItem('USER')).id}
					that.ws.send(JSON.stringify(message));
				}
				
				//接听服务器发回的信息并处理展示
				this.ws.onmessage = function (data) {
					console.log('接收到来自服务器的消息：');
					console.log(data);
					console.log(JSON.parse(data.data));
					//列表赋值
					if(JSON.parse(data.data).type!='@heart@'){
						that.tableData=JSON.parse(data.data)
					}
					
				}
				// 监听连接关闭事件
				this.ws.onclose = function () {
					// 监听整个过程中websocket的状态
					// console.log('ws连接状态3：' + that.ws.readyState);
				}
				// 监听并处理error事件
				this.ws.onerror = function (error) {
					console.log('ws连接状态4：' + that.ws.readyState);
					console.log(error);
				}
				
			},
			//跳转
			tozbgl(){
				this.$router.push({path:'/zhibotongji/zhuboguanli',query:{type:2}})
			},
			//下载模板
			downDate:function(){
            	const a = document.createElement('a');
				a.setAttribute('download', '直播统计使用说明.pdf');
				a.setAttribute('href', this.url + 'static/zbdk.pdf');
				a.click();
          	},
			//时间差
			timediff(begin_time){

				var end_time = this.getNowDate()
				//年月日时分秒转换为时间戳
				let beginTime = (new Date(begin_time).getTime()) / 1000;
				let endTime = (new Date(end_time).getTime()) / 1000;
				var starttime = ''
				var endtime = ''
				if (beginTime < endTime) {
					starttime = beginTime;
					endtime = endTime;
				} else {
					starttime = endTime;
					endtime = beginTime;
				}
				//计算天数
				var timediff = endtime - starttime;
				var days = parseInt(timediff / 86400);
				//计算小时数
				var remain = timediff % 86400;
				var hours = parseInt(remain / 3600);
				//计算分钟数
				var remain = remain % 3600;
				var mins = parseInt(remain / 60);
				var res =  hours + '小时' + mins + '分';
				return res;
			},
			//获取当前时间年月日时分秒
			getNowDate(){
				var date = new Date();
				var sign2 = ":";
				var year = date.getFullYear() // 年
				var month = date.getMonth() + 1; // 月
				var day = date.getDate(); // 日
				var hour = date.getHours(); // 时
				var minutes = date.getMinutes(); // 分
				var seconds = date.getSeconds() //秒
				var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
				var week = weekArr[date.getDay()];
				// 给一位数的数据前面加 “0”
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (day >= 0 && day <= 9) {
					day = "0" + day;
				}
				if (hour >= 0 && hour <= 9) {
					hour = "0" + hour;
				}
				if (minutes >= 0 && minutes <= 9) {
					minutes = "0" + minutes;
				}
				if (seconds >= 0 && seconds <= 9) {
					seconds = "0" + seconds;
				}
				// console.log(year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds)
				return year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds;
			},
			//主播列表
			zblist(){
				axios.get('/api/live-stream/streamer/list').then((response)=>{
					// console.log(response.data.data)
					this.zblistdata=response.data.data
				})
			},
			//直播类型
			zbtype(){
				axios.get('/api/live-stream/type').then((response)=>{
					// console.log(response.data.data)
					for (let i in response.data.data) {
						// console.log(i)
						this.zbtypedata.push({'label':response.data.data[i],'value':i})
					}
				})
			},
			//当前直播类型
			nowtype(val){
				console.log(val)
				//直播标题
				this.zbtitle(val.value)
				this.choosezbtitle=''
				this.zbtitledata=[]
			},
			//直播标题
			zbtitle(type,title){

				axios.get('/api/live-stream/title',{
					params:{
						type:type
					}
				}).then((response)=>{
					for (let i in response.data.data) {
						// console.log(response.data.data[i])
						this.zbtitledata.push({'label':i,'value':response.data.data[i]})

						if(this.isreplace){

							if(title==i){

								this.choosezbtitle={'label':i,'value':response.data.data[i]}
								console.log(this.choosezbtitle)
							}
						}
					}
				})
			},

			//在播列表
			getlist(){
				axios.get('/api/live-stream/list').then((response)=>{
					// console.log(response)
					this.tableData=response.data.data
					// if(this.tableData.length!=0){
					// 	// console.log('有值')
					// 	if(!this.xunhuan){
					// 		this.xunhuan = setInterval(()=>{
					// 			this.getlist()
								
					// 		},5000)
					// 	}
					// }else{
					// 	console.log('无值')
					// 	clearInterval(this.xunhuan);
					// 	this.xunhuan=''
					// }
				})
			},
			//下播
			handleEdit(id){
                this.$confirm('是否确认下播?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
					axios.post('/api/live-stream/streamer/down',{
						id:id
					}).then((response)=>{
						this.$message({
							type: 'success',
							message: '操作成功!'
						});
						//在播列表
						this.getlist()
					})
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
			//打卡
            daka(){
				this.isreplace=false
                this.dakashow=true
				this.choosezb=''
				this.choosezbtype=''
				this.choosezbtitle=''
				this.zbtitledata=[]
            },
			//替换上播
			replace(row){
				console.log(row)
				this.replaceid=row.streamer_id
				this.isreplace=true
				this.dakashow=true
				this.choosezb=''
				this.choosezbtype=''
				this.choosezbtitle=''
				this.zbtitledata=[]
				//赋值直播类型
				for(var x=0;x<this.zbtypedata.length;x++){
					if(this.zbtypedata[x].label==row.type){
						console.log(this.zbtypedata[x])
						this.choosezbtype=this.zbtypedata[x]
						//直播标题
						this.zbtitle(this.zbtypedata[x].value,row.title)
					}
				}

			},
			//开始直播
            startzb(){
				if(this.choosezb==''){
					this.$message.error('请选择主播');
					return
				}else if(this.choosezbtype==''){
					this.$message.error('请选择直播类型');
					return
				}else if(this.choosezbtitle==''){
					this.$message.error('请选择直播标题');
					return
				}

				// console.log(this.choosezb.name,this.choosezbtype.label,this.choosezbtitle.label)

				var textval = this.choosezb.name+'-'+this.choosezbtype.label+'-'+this.choosezbtitle.label+' 是否确认开启直播'
                this.$confirm(textval, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

					if(this.isreplace){
						//替换直播
						axios.post('/api/live-stream/replace/streamer',{
							old_streamer_id:this.replaceid,
							title:this.choosezbtitle.label,
							streamer_id:this.choosezb.id,
						}).then((response)=>{
							if(response.data.msg.code==0){
								this.dakashow=false
								this.$message({
									type: 'success',
									message: '操作成功!'
								});
								//在播列表
								this.getlist()
							}else{
								this.$message.error(response.data.msg.info);
							}

						})
					}else{
						//新建直播
						axios.post('/api/live-stream/create',{
							streamer_id:this.choosezb.id,
							type:this.choosezbtype.label,
							title:this.choosezbtitle.label,
							source:this.choosezbtitle.value,
						}).then((response)=>{
							if(response.data.msg.code==0){
								this.dakashow=false
								this.$message({
									type: 'success',
									message: '操作成功!'
								});
								//在播列表
								this.getlist()
							}else{
								this.$message.error(response.data.msg.info);
							}

						})
					}

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            }

		}
	}
</script>


<style lang="scss" scoped>
	.index {
		.t_table_box{
		   
        padding:0 20px;
		    margin-left: auto;
		    margin-right: auto;
		    margin-top: 50px;
		}
		.t_daka_box{
		    display: flex;
		    justify-content: center;
		    margin-bottom: 40px;
		}
		.t_daka_btn{
		    width: 160px;
		    height: 160px;
		    background-color: #FF5252;
		    color: white;
		    display: flex;
		    align-items: center;
		    justify-content: center;
		    cursor: pointer;
		}
		.t_select_box{
		    display:block;
		    width: 270px;
		    margin-right: 20px;
		}

		.see {
			color: #409EFF;
			margin: 20px 0;
			cursor: pointer;
		}

		.cpflex {
			display: flex;
			flex-wrap: wrap;

			.el-form-item {
				margin-bottom: 0px;
			}
		}

		.kucun {
			/deep/ .el-input {
				width: 200px;
			}

			.list {
				display: flex;
				text-align: center;
				border-bottom: 1px #EAEAEA solid;

				.bor1 {
					border-right: 1px #EAEAEA solid;

					i {
						color: #409EFF;
						font-size: 14px;
						margin-left: 10px;
						cursor: pointer;
					}
				}

				.th {
					background: #F9F9F9;
					line-height: 45px;
					flex: 1;
					font-size: 14px;
					box-sizing: border-box;
				}

				.td {
					line-height: 45px;
					font-size: 14px;
					flex: 1;
					box-sizing: border-box;
					color: #666;
				}

				.td2 {
					flex: 1.5
				}
			}
		}



				.o_ul {
					background: #F9F9F9;
					display: flex;

					.o_li {
						flex-basis: 160px;
						line-height: 45px;
						display: block;
						color: #727272;
						border-top: 3px #F9F9F9 solid;
						font-size: 14px;
						text-align: center;
					}

					.act {
						border-top: 3px #DD2727 solid;
						background: #FFFFFF;
					}
				}

				.title {
					border-bottom: 1px #EAEAEA solid;
					line-height: 45px;
					padding-left: 30px;
					font-size: 16px;
					background: #F9F9F9;
					color: #727272
				}

				.bsm {
					padding: 20px 20px 0 20px;

					/deep/ .el-input {
						width: 220px;
					}
				}

				.row2 {
					color: #FFF;
					margin-top: 20px;

					a {
						color: #FFF;
					}
				}

				.con {
					margin: 20px;
					border: 1px #EAEAEA solid;

					.list {
						display: flex;
						text-align: center;
						border-bottom: 1px #EAEAEA solid;

						.bor1 {
							border-right: 1px #EAEAEA solid;

							i {
								color: #409EFF;
								font-size: 14px;
								margin-left: 10px;
								cursor: pointer;
							}
						}

						.th {
							background: #F9F9F9;
							line-height: 45px;
							flex: 1;
							font-size: 14px;
							box-sizing: border-box;
						}

						.td {
							line-height: 45px;
							font-size: 14px;
							flex: 1;
							box-sizing: border-box;
							color: #666;
						}

						.td2 {
							flex: 1.5
						}
					}
				}

				.el-pagination {
					text-align: right;
					margin-right: 20px;
					padding-bottom: 50px;
				}


	}
</style>
